package _tema6.srv;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;

public class Servidor {
	private ServerSocket server;
	private final int PORT = 7920;
	private final int wait = 50;
	private boolean flag = true;
	
	public Servidor() {
		iniciarServer();
		aceptarCliente();
		cerrarServer();
	}

	void iniciarServer() {
    	try {
    		server = new ServerSocket(PORT);
    		server.setSoTimeout(wait * 1000);
    		System.out.print("HostAddress: ");
    		System.out.print(InetAddress.getLocalHost().getHostAddress());
    		System.out.print("\tPort: ");
     		System.out.println(server.getLocalPort());
    	} catch (IOException e) {
    		System.out.println(e.getMessage());
    		System.exit(1);
    	}     	
	}
	
	void aceptarCliente() {
    	try {
    		while(true){
    			System.out.println("elooo1");
    			Sesion sesion = new Sesion(server.accept());
    			System.out.println("elooo2");
    			sesion.start();
    		}
    	} catch (SocketTimeoutException e) {
    		System.out.println(e.getMessage());
     	} catch (IOException e) {
     		System.out.println(e.getMessage());
    	}     	
	}	
	
	void cerrarServer() {
    	try {
      		server.close();
    		System.out.print("ServerSocket cerrado:\t");
    		System.out.println(server.isClosed()); 
    	} catch (IOException e) {
    		System.out.println(e.getMessage());
    		System.exit(1);
    	}     	
	}
	
	
	
}
